import { fileURLToPath, URL } from 'node:url'
import AutoImport from 'unplugin-auto-import/vite'
import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import { createStyleImportPlugin, VxeTableResolve } from 'vite-plugin-style-import'
import { resolve } from 'path'
import { chunkSplitPlugin } from 'vite-plugin-chunk-split'
/** 路径查找 */
const pathResolve = (dir: string): string => {
  return resolve(__dirname, '.', dir)
}
// https://vitejs.dev/config/
export default ({ mode }) =>
  defineConfig({
    plugins: [
      vue(),
      AutoImport({
        resolvers: [ElementPlusResolver()]
      }),
      Components({
        resolvers: [ElementPlusResolver()],
        directoryAsNamespace: true
      }),
      createStyleImportPlugin({
        resolves: [VxeTableResolve()]
      })
    ],
    server: {
      //@ts-ignore 端口号
      port: loadEnv(mode, process.cwd()).VITE_PORT || 3000,
      host: '0.0.0.0',
      // 本地跨域代理 https://cn.vitejs.dev/config/server-options.html#server-proxy
      proxy: {
        '/api': {
          target: loadEnv(mode, process.cwd()).VITE_API_SERVER,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, '/api')
        }
      }
    },
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url))
      }
    },
    build: {
      sourcemap: false,
      // 消除打包大小超过500kb警告
      chunkSizeWarningLimit: 4000,
      rollupOptions: {
        input: {
          index: pathResolve('index.html')
        },
        // 静态资源分类打包
        output: {
          manualChunks(id, { getModuleInfo }) {
            if (id.includes('node_modules')) {
              // console.log(id.toString().split('node_modules/')[1].split('/')[1]);
              return id.toString().split('node_modules/')[1].split('/')[1].toString()
            }
            const reg = /(.*)\/src\/utils\/(.*)/
            if (reg.test(id)) {
              const importersLen = getModuleInfo(id)?.importers.length
              // 被多处引用
              if (importersLen && importersLen > 1) return 'common'
            }
          },
          chunkFileNames: 'static/js/[name]-[hash].js',
          entryFileNames: 'static/js/[name]-[hash].js',
          assetFileNames: 'static/[ext]/[name]-[hash].[ext]'
        }
      }
    }
  })
